<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input
        v-model="params.name"
        placeholder="请输入菜品名称"
        clearable
        size="small"
        style="width: 180px"
        class="filter-item"
        @change="handleSearch"
        @clear="handleSearch"
      >
        <i
          slot="prefix"
          class="el-input__icon el-icon-search"
          @click="handleSearch"
        />
      </el-input>
      <el-button
        class="filter-item"
        type="primary"
        size="small"
        @click="handleAdd"
      >
        <i class="el-icon-edit" />
        添加
      </el-button>
      <el-button
        type="danger"
        size="small"
        :disabled="selectedRows.length === 0"
        @click="handleBatchDelete(selectedRows)"
      >
        批量删除({{ selectedRows.filter((item) => item.status === 0).length }})
      </el-button>
      <el-button
        type="danger"
        size="small"
        :disabled="
          selectedRows.length === 0 ||
          selectedRows.filter((item) => item.status === 1).length === 0
        "
        @click="handleBatchDisable"
      >
        批量停售 ({{ selectedRows.filter((item) => item.status === 1).length }})
      </el-button>
      <el-button
        type="success"
        size="small"
        :disabled="
          selectedRows.length === 0 ||
          selectedRows.filter((item) => item.status === 0).length === 0
        "
        @click="handleBatchEnable"
      >
        批量启售 ({{ selectedRows.filter((item) => item.status === 0).length }})
      </el-button>
    </div>
    <el-table :data="list" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" />
      <el-table-column type="index" width="50" label="序号" />
      <el-table-column prop="name" width="120" label="菜品名称" />
      <el-table-column width="120" label="图片">
        <template slot-scope="{ row }">
          <el-image
            style="width: 50px; height: 50px"
            :src="`${env}/common/download?name=${row.image}`"
            :preview-src-list="[`${env}/common/download?name=${row.image}`]"
          >
          </el-image>
        </template>
      </el-table-column>
      <el-table-column prop="categoryName" width="150" label="菜品分类" />
      <el-table-column prop="price" width="200" label="售价" />
      <el-table-column prop="status" label="售卖状态" min-width="100">
        <template slot-scope="{ row }">
          <el-tag v-if="row.status === 1" type="success">启售</el-tag>
          <el-tag v-else type="danger">停售</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="250">
        <template slot-scope="{ row }">
          <div>创建时间：{{ row.createTime }}</div>
          <div>更新时间：{{ row.updateTime }}</div>
        </template>
      </el-table-column>
      <el-table-column
        fixed="right"
        label="操作"
        width="250"
        style="display: flex; gap: 10px"
      >
        <template slot-scope="{ row }">
          <div style="display: flex; gap: 5px">
            <el-button
              type="primary"
              size="small"
              link
              @click="handleUpdate(row)"
            >
              编辑
            </el-button>
            <div>
              <el-button
                v-if="row.status === 1"
                type="warning"
                size="small"
                link
                @click="handleDisable(row)"
              >
                停售
              </el-button>
              <el-button
                v-else
                type="success"
                size="small"
                link
                @click="handleEnable(row)"
              >
                启售
              </el-button>
            </div>
            <el-button
              type="danger"
              size="small"
              link
              @click="handleBatchDelete([row])"
            >
              删除
            </el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <Pagination
      :total="total"
      :page.sync="params.page"
      :size.sync="params.pageSize"
      @pagination="loadData"
    />
    <edit
      :value.sync="editDrawer"
      :row="currentRow"
      @success="success"
      @closed="editDrawer = false"
    />
  </div>
</template>

<script>
import edit from "./edit.vue";
import { Message } from "element-ui";
import { pageList, deleteMenu, disableMenu, enableMenu } from "@/api/menu";
import Pagination from "@/components/Pagination/index.vue";
import { debounce } from "lodash";
export default {
  name: "Menu",
  components: {
    edit,
    Pagination,
  },
  data() {
    return {
      currentRow: {},
      editDrawer: false,
      env: process.env.VUE_APP_BASE_API,
      list: [],
      total: 0,
      params: {
        page: 1,
        pageSize: 20,
        name: "",
      },
      selectedRows: [],
    };
  },
  mounted() {
    this.loadData();
  },
  methods: {
    loadData() {
      pageList(this.params).then((res) => {
        const { data } = res;
        this.total = data.total || 0;
        this.list = data.records;
      });
    },
    // 防抖：在首次调用时立即触发一次，之后两秒内无论调用多少次都不会再触发。两秒之后再次调用，依然是立刻触发。
    handleSearch: debounce(
      function () {
        this.loadData();
      },
      2000,
      { leading: true, trailing: false }
    ),
    handleSelectionChange(selection) {
      this.selectedRows = selection;
    },
    handleAdd() {
      this.editDrawer = true;
      this.currentRow = null;
    },
    handleUpdate(row) {
      this.editDrawer = true;
      this.currentRow = row;
    },
    handleDisable(row) {
      const ids = Array.isArray(row)
        ? row.map((item) => item.id).join(",")
        : row.id;
      disableMenu(ids)
        .then((res) => {
          Message({
            message: "禁用成功",
            type: "success",
          });
          this.loadData();
        })
        .catch((err) => {
          Message({
            message: err.msg,
            type: "info",
          });
        });
    },
    // 菜品删除
    handleDelete(row) {
      const ids = Array.isArray(row)
        ? row.map((item) => item.id).join(",")
        : row.id;
      this.$confirm("确认要删除该菜品吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          // 使用批量删除的接口（示例为deleteMenuByIds，可根据实际API方法名替换）
          deleteMenu(ids).then(() => {
            this.$message({
              type: "success",
              message: "删除成功!",
            });
            this.loadData();
          });
        })
        .catch(() => {});
    },
    // 批量删除
    handleBatchDelete(rows) {
      if (rows.length === 0) {
        this.$message({
          type: "warning",
          message: "请先选择要删除的数据",
        });
        return;
      }

      // 获取选中数据的ID
      const ids = rows.map((item) => item.id).join(",");
      this.$confirm(`确认要删除选中的 ${rows.length} 个菜品吗？`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        deleteMenu(ids).then(() => {
          this.$message({
            type: "success",
            message: "删除成功!",
          });
          this.loadData();
        });
      });
    },
    // 批量停售
    handleBatchDisable() {
      if (this.selectedRows.length === 0) {
        this.$message({
          type: "warning",
          message: "请先选择要停售的数据",
        });
        return;
      }

      // 过滤出当前启售状态的菜品
      const enableItems = this.selectedRows.filter((item) => item.status === 1);
      if (enableItems.length === 0) {
        this.$message({
          type: "warning",
          message: "选中的数据中没有启售状态的菜品",
        });
        return;
      }

      const ids = enableItems.map((item) => item.id).join(",");
      this.$confirm(
        `确认要停售选中的 ${enableItems.length} 个菜品吗？`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          disableMenu(ids)
            .then(() => {
              this.$message({
                type: "success",
                message: "停售成功!",
              });
              // 清空选中数据
              this.selectedRows = [];
              this.loadData();
            })
            .catch((err) => {
              this.$message({
                type: "error",
                message: err.msg || "停售失败",
              });
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消停售",
          });
        });
    },
    // 批量启售
    handleBatchEnable() {
      if (this.selectedRows.length === 0) {
        this.$message({
          type: "warning",
          message: "请先选择要启售的数据",
        });
        return;
      }

      // 过滤出当前停售状态的菜品
      const disableItems = this.selectedRows.filter(
        (item) => item.status === 0
      );
      if (disableItems.length === 0) {
        this.$message({
          type: "warning",
          message: "选中的数据中没有停售状态的菜品",
        });
        return;
      }

      const ids = disableItems.map((item) => item.id).join(",");
      this.$confirm(
        `确认要启售选中的 ${disableItems.length} 个菜品吗？`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "success",
        }
      )
        .then(() => {
          enableMenu(ids)
            .then(() => {
              this.$message({
                type: "success",
                message: "启售成功!",
              });
              // 清空选中数据
              this.selectedRows = [];
              this.loadData();
            })
            .catch((err) => {
              this.$message({
                type: "error",
                message: err.msg || "启售失败",
              });
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消启售",
          });
        });
    },
    success() {
      this.editDrawer = false;
      this.loadData();
    },
  },
};
</script>

<style scoped lang="scss">
.filter-container {
  .el-input {
    i {
      cursor: pointer;
    }
  }
}
</style>
